package com.meichis.yndms.hybrid;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

public class MCSChromeClient extends WebChromeClient {
	private HybridInterface hybrid; 

	public MCSChromeClient(HybridInterface hybrid) {
		this.hybrid = hybrid;
	}

 

	@Override
	public void onProgressChanged(WebView view, int progress) {
		MCWebView mcview = (MCWebView) view;

		try {
			if (progress == 100)
				mcview.progressbar.setVisibility(View.GONE);
			else {
				if (mcview.progressbar.getVisibility() == View.GONE)
					mcview.progressbar.setVisibility(View.VISIBLE);
				mcview.progressbar.setProgress(progress);
			}  
		} catch (Exception e) {
		}
		
		super.onProgressChanged(view, progress);
	}

	/**
	 * Tell the client to display a confirm dialog to the user.
	 * 
	 * @param view
	 * @param url
	 * @param message
	 * @param result
	 */
	@Override
	public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
		AlertDialog.Builder dlg = new AlertDialog.Builder(hybrid.getActivity());
		dlg.setMessage(message);
		dlg.setTitle("Confirm");
		dlg.setCancelable(true);
		dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				result.confirm();
			}
		});
		dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				result.cancel();
			}
		});
		dlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				result.cancel();
			}
		});
		dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
			// DO NOTHING
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					result.cancel();
					return false;
				} else
					return true;
			}
		});
		dlg.create();
		dlg.show();
		return true;
	}

	public void openFileChooser(ValueCallback<Uri> uploadMsg) {
		this.openFileChooser(uploadMsg, "*/*");
	}

	public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
		this.openFileChooser(uploadMsg, acceptType, null);
	}

	public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
		String IMAGE_UNSPECIFIED = "*/*";
		innerIntent.addCategory(Intent.CATEGORY_OPENABLE);
		innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
		Intent wrapperIntent = Intent.createChooser(innerIntent, "File Browser");
		hybrid.getActivity().startActivityForResult(wrapperIntent, JavaScriptInterface.CONTEXT_RETURNGETFILE);
	}

}
